package ch.supsi.template.money;

import java.util.ArrayList;
import java.util.List;

public class MoneyBag extends AbstractMoney {
    private List<Money> fMonies = new ArrayList<Money>();

    public MoneyBag(Money m1, Money m2) {

        appendMoney(m1);
        appendMoney(m2);
    }

    public MoneyBag(Money bag[]) {
        for (Money money : bag) {
            appendMoney(money);
        }
    }

    //costruttori aggiunti

    public MoneyBag(Money m, MoneyBag mb) {
        appendMoneyBag(mb);
        appendMoney(m);
    }

    public MoneyBag(MoneyBag mb1, MoneyBag mb2) {
        appendMoneyBag(mb1);
        appendMoneyBag(mb2);
    }

    public void appendMoney(Money m) {
        if (m.getAmount() != 0) {
            int position = findMoneyWithSameCurrency(fMonies, m.getCurrency());
            if (position == -1) {
                fMonies.add(m);
            } else {
                Money existingMoney = fMonies.remove(position);
                Money result = (Money) m.addMoney(existingMoney);
                appendMoney(result);
            }
        }
    }

    //...

    //da IMoney
    //non considera l'ordine

    public boolean equals(Object mb) {
        if ((mb instanceof MoneyBag) &&
                (fMonies.size() == ((MoneyBag) mb).getMoneyList().size())) {
            List moneyListFromMoneyBag = ((MoneyBag) mb).getMoneyList();
            for (Money money : fMonies) {
                if (moneyListFromMoneyBag.indexOf(money) == -1) {
                    return false;
                }
            }

            return true;
        }

        return false;
    }

    public IMoney addMoney(Money m) {
        return new MoneyBag(m, this).simplify();
    }

    public IMoney addMoneyBag(MoneyBag b) {
        return new MoneyBag(b, this).simplify();
    }

    //per Visitor
    /*
    public IMoney add(IMoney m) {
        return ((AbstractMoney) m).addMoneyBag(this);
    } */

    public IMoney multiply(int factor) {
        List tempResults = new ArrayList();
        for (Money money : getMoneyList()) {
            tempResults.add(money.multiply(factor));
        }
        return new MoneyBag((Money[]) tempResults.toArray(new Money[tempResults.size()]));
    }

    private List<Money> getMoneyList() {
        return fMonies;
    }

    private void appendMoneyBag(MoneyBag mb) {
        for (Money money : mb.getMoneyList()) {
            appendMoney(money);
        }
    }

    private int findMoneyWithSameCurrency(List monies, String currency) {
        for (int i = 0; i < monies.size(); i++) {
            Money money = (Money) monies.get(i);
            if (money.getCurrency().equals(currency)) {
                return i;
            }
        }
        return -1;
    }

    private IMoney simplify() {
        if (fMonies.size() == 1) {
            return fMonies.get(0);
        }
        return this;
    }

}